/*
 * Untity function
 */
String.format = function() {
	if (arguments.lengh == 0)
		return null;
	var context = arguments[0], index = arguments.length;
	while (index--)
		context = context.replace(new RegExp("\\{" + index + "\\}", "gm"),
				arguments[index]);
	return context;
}
/*
 * List functions
 */
// Generate list-items from DB
function initListItem(){
	$.ajax({
		type: 'GET',
		cache: false,
		url: 'ajax/ajax.php',
		data: {action:'lists',rnd:Math.random()},
		dataType: 'json',
		complete: function(){
			initListsTab();
			initListItemBar();
			initListItemContext();
			initTaskItemContext();
		},
		success: function(result){
			/*
			  var list_item_context=new Array({name:'刪除',id:'del'},{name:'重新命名',id:'ren'}); //Create list-item-context for each list-item
			  $.each(list_item_context,function(i){ 
			  	var context_item=$("<li></li>");
			  	var obj=list_item_context[i]; context_item.text(obj.name);
			  	context_item.attr('id',obj.id);
			  	$('#list_item_context').append(context_item); })
			 */
			// Created list-item to list-item-bar
			$.each(result,function(i){
				var id=result[i].id,name=result[i].name;
				/*
				var list_item=$("<li>");
				list_item.addClass('list_item');
				list_item.attr('id','list_item_'+id);
				list_item.append($("<a href='#tab_"+id+"'>"+name+"</a>"));
				*/
				var list_item=makeListItem(id,name);
				$('#list_items_bar').append(list_item);
				/*
				var list_item_content=$("<div>");
				list_item_content.attr('id','task_'+id);
				$("#lists_tab").append(list_item_content);
				*/
				initTaskItem(id);
			});
			// end create list-item
		}
		// end ajax success function
	});
	// end ajax function	
}
//Make jQuery object of list-item
function makeListItem(id,name){
	var classes=['list_item','ui-state-default','ui-corner-top'],list_prefix='list_item_',task_prefix='task_',jObj=$("<li/>");
	jObj.attr('id',list_prefix+id).addClass(classes.join(' '));
	jObj.append($(String.format("<a href='#{1}{2}'>{3}</a>",task_prefix, id, name)));
	return jObj;
}
function initListsTab(){
	// Enable list-item to tabs
	$('#lists_tab').tabs({
		//Init task-item context when tab show time
		show: function(event,ui){
			initTaskItemContext();
			initTaskTabContext();	
		}
	});
}
//Enable list-item-bar to sortable
function initListItemBar(){
	$('#list_items_bar').sortable({
		// Update position of list-item after reorder.
		update: updateListItemPos
	});
	// end enable list-item-bar to sortable	
}
//Create list-item-context for each list-item
function initListItemContext(){
	$('.list_item').jeegoocontext('list_item_context',{
		onSelect: function(evt,obj){
			var list_item=$(obj);
			switch($(this).attr('id')){
			// Confim delete list-item
			case 'del_list':
				$("#list_item_dialog").text("是否要刪除此清單(包含所有的任務)?").dialog({
					title: "刪除清單",
					show: "highlight",
					buttons: {
						"確定": function(){
							var list_id=list_item.attr('id');
							delListItem(list_item,list_id);
							$(this).dialog('close');
						},
						"取消": function(){
							$(this).dialog('close');
						}
					}
				});
				break;
			// Get new name
			case 'ren_list':
				var input_box = $("<input id='rename_list_name'/>");
				input_box.addClass('ui-widget-content ui-corner-all');
				//TODO: Vaild text field 
				$("#list_item_dialog").text("輸入欲更改的清單名稱?").append(input_box).dialog({
						title:"重新命名清單",
						modal: true,
						buttons:{
							"確定": function(){
								var list_id = list_item.attr('id');
								var list_name=$("#rename_list_name").val();
								renListItem(list_item,list_id,list_name);
								$(this).dialog('close');
							},"取消": function(){
								$(this).dialog('close');
							}
						}
				});
				break;
			}
		}
	});
	// end create list-item-context	
}
function addListItem(list_name){
	$.ajax({
		type: 'GET',
		url: 'ajax/ajax.php',
		data: {action:'new_list',name:list_name,rnd:Math.random()},
		success: function(result){
			// return false if add list-item failure,return list id  if successed.
			// alert(result);
			if (result!='false'){
				/*
				var new_list_item=$("<li></li>")
				new_list_item.text(list_name);
				new_list_item.attr('class','list_item');
				new_list_item.attr('id','list_item_'+result);
				*/
				var new_list_item=makeListItem(result,list_name);
				$("#list_items_bar").append(new_list_item);
				
				//reload list-item context
				initListItemContext();
				initTaskItem(result);
				initListsTab();
			}
		}
		// end ajax success function
	});	
}
function renListItem(list_item,list_id,list_name){
	$.ajax({
		type: 'GET',
		url: 'ajax/ajax.php',
		data: {action: 'ren_list',id:list_id,name:list_name,rnd:Math.random()},
		success: function(result){
			//alert(result);
			if (result=='true'){
				list_item.children('a').text(list_name);
			}
		}
		// end ajax success funtion
	});
}
function delListItem(list_item,list_id){
	$.ajax({
		type: 'GET',
		url: 'ajax/ajax.php',
		data: {action:'del_list',id:list_id,rnd:Math.random()},
		success: function(result){
			if (result=='true'){
				var list_item_index=$('.list_item').index(list_item);
				$("#lists_tab").tabs('remove',list_item_index);
			}
		}
		// end ajax success function
	});	
}
function updateListItemPos(event,ui){
	var after_sort=$(this).sortable('toArray');
	$.ajax({
		type: 'GET',
		cache: false,
		url: 'ajax/ajax.php',
		data: {action:'reorder',position:after_sort,rnd:Math.random()},
		success: function(result){
			// alert(result);
		}
		// end ajax success function
	});	
}

//Initial Add new-list button
function initAddListButton(){
	$("#new_list_item").button({
		icons:{primary:'ui-icon-document'}
	}).click(function(){
		var input_box=$("<input id='new_list_name'/>");
		input_box.addClass('ui-widget-content ui-corner-all');
		$("#list_item_dialog").text("輸入新增清單名稱?").append(input_box).dialog({
			title: '新增清單',
			modal: true,
			buttons:{
				'確定': function(){
					// TODO: Regualr list-name format
					list_name=$.trim($('#new_list_name').val());
					addListItem(list_name);
					$(this).dialog('close');
				},'取消': function(){
					$(this).dialog('close');
				}
			}
		});

	});
	// end init new-list button
}

$(document).ready(function(){	
	initAddListButton();
	initListItem();


});

